;(function ($, window) {
    function fileQueued(file, up) {
        var $item = $('#media-item-' + file.id);
        if ($item.data('last-err') == file.id) {
            return;
        }
        $('#media-items').append('<div id="media-item-' + file.id + '" class="media-item">'
        + '<div class="progress"><div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">0%</div></div>'
        + '<div class="filename original"> ' + file.name + ' </div></div>');
    }

    function fileError(file, message, up) {
        var $item = $('#media-item-' + file.id),
            html = '<p><span class="name">' + file.name + '</span>' + message + '</p>';
        if ($item.length) {
            if (!$item.hasClass('error')) {
                $item.addClass('error');
            }
            $item.html(html);
        } else {
            $('#media-items').append('<div id="media-item-' + file.id + '" class="media-item error">' + html + '</div>');
        }
    }

    function uploadProgress(file, up) {
        var html = file.percent + '%',
            $item = $('#media-item-' + file.id);

        $item.find('.progress-bar')
            .width(($item.find('.progress').width() * file.loaded) / file.size)
            .attr('aria-valuenow', file.percent)
            .html(html);
    }

    function uploadSuccess(file, response, up) {
        var $item = $('#media-item-' + file.id),
            attachment;

        $item.find('.progress-bar').html('处理中...');

        try {
            response = $.parseJSON(response.response);
        } catch (e) {
            console.log(e);
            fileError(file, '服务器发生错误', up);
            return;
        }

        if (!response.success) {
            fileError(file, response.errors.join('</br>'), up);
        } else {
            attachment = response.attachment;
            var html = '<img class="pinkynail" src="' + attachment.iconUrl + '">'
                + '<a target="_blank" href="' + attachment.editLink + '" class="edit-attachment">编辑</a>'
                + '<div class="filename new">' + attachment.title + '<strong>' + attachment.fileSize +'</strong></div>'

            $item.html(html);
        }
    }

    $(document).ready(function () {
        $.each(window.YCMF.uploaderInit, function (i, options) {
            var uploader,
                pluploadOptions = options['plupload'];

            pluploadOptions['init'] = {
                Init: function (up, params) {
                    var $pluploadContainer = $('#' + up.getOption('container'));
                    if (up.features.dragdrop) {
                        $pluploadContainer.addClass('drag-drop');
                        console.log($pluploadContainer);
                        $('.drag-drop-area', $pluploadContainer).bind('dragover.ycmf-uploader',function () {
                            $pluploadContainer.addClass('drag-over');
                        }).bind('dragleave.ycmf-uploader, drop.ycmf-uploader', function () {
                            $pluploadContainer.removeClass('drag-over');
                        });
                    } else {
                        $pluploadContainer.removeClass('drag-drop');
                        $('.drag-drop-area', $pluploadContainer).unbind('.ycmf-uploder');
                    }
                },

                PostInit: function() {
                    console.log('postInit');
                },

                UploadFile: function() {
                    console.log('uploadFile');
                },

                FilesAdded: function(up, files) {
                    plupload.each(files, function (file) {
                        fileQueued(file, up);
                    });
                    up.refresh();
                    up.start();
                },

                FileUploaded: function(up, file, resp) {
                    uploadSuccess(file, resp);
                },

                UploadProgress: function(up, file) {
                    uploadProgress(file, up);
                },

                UploadComplete: function(up, files) {
                    console.log('uploadComplete');
                },

                Error: function(up, err) {
                    fileError(err.file, err.message, up);
                    up.refresh();
                }
            };

            uploader = new plupload.Uploader(pluploadOptions);
            uploader.init();
        });
    });
})(jQuery, window);